#include "httpclient.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextCodec>
#include <QtNetwork>
#include <QHostInfo>
#include <QNetworkInterface>
#include "tdebug.h"
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonDocument>
#include "Device/DeviceState/devicestate.h"
#include "Setting/Communication/serversettings.h"
#include "common.h"
#include "globalvar.h"
#include "videoip.h"
#include <QDebug>


//#define IP_ADRESS "192.168.168.48"
//#define HOST_IP "http://192.168.168.48/"
//#define REGISTER_DEVICE_INFO_URL    HOST_IP"api/device_info/"   /*向Http Server 发送注册设备信息的url*/
//#define DEVICE_DETAIL_URL           HOST_IP"api/device_detail/"   /*向Http Server发送设备明细的url*/
//#define USER_PERMISSION_URL         HOST_IP"production_staff/api/production_user_permission/"
//#define USER_URL                    HOST_IP"user/api/user_info/"  //23456789
//#define POST_ORDER_URL              HOST_IP"production_order/api/production_order_state/"


#define GONGZHUANG                  "api/device_task_moduleid/"
#define DIANJIAN                    "api/device_inspection/"
#define Material                    "api/device_task_material/"
#define QC                          "api/device_task_qc/"
#define FIRST_CHECK                 "api/device_task_fai/"
#define OPERATOR                    "api/device_task_operator/"
#define DEVICE_TASK_INFO            "api/device_task_info/"
#define NEW_PRODUCT_INFO            "api/product_property/"
#define UPDATE_TASK_ORDER_INFO      "api/task_info/"      /*新增/更新任务订单信息*/
#define UPDATE_ORDER_DEVICE_INFO    "api/device_property/"   /*向Http Server 更新该订单的设备属性url*/
#define REGISTER_DEVICE_INFO_URL    "api/device_info/"   /*向Http Server 发送注册设备信息的url*/
#define DEVICE_DETAIL_URL           "api/device_detail/"   /*向Http Server发送设备明细的url*/
#define USER_PERMISSION_URL         "production_staff/api/production_user_permission/"
#define USER_URL                    "user/api/user_info/"  //23456789
#define POST_ORDER_URL              "production_order/api/production_order_state/"
#define POST_WARN_URL               "api/device_task_alarm/"  /*Alarm info post to server*/
#define HJWELDER_ENERGY_PROPERTY    "api/HJWelderEnergy_property/"  /*豪精点焊能耗管控*/

HttpClient::HttpClient(QString deviceType,QString deviceId,QObject *parent) :
    QObject(parent),m_deviceType(deviceType),m_deviceId(deviceId)
  ,m_permission(-1)
{
    network_manager = new QNetworkAccessManager(this);
    //    mServerSetting = ServerSettings::getServerSettings();
    //qDebug()<<"++++++++++++++Debbug++++++++++++++";
    mServerSetting = "http://" + ServerSettings::getServerIP() + "/";
    QObject::connect(network_manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinish(QNetworkReply*)));
    PingThread *pingThread = new PingThread(/*IP_ADRESS*/ServerSettings::getServerIP());
    connect(pingThread,SIGNAL(ipstatus(bool)),this,SLOT(receiIpStatus(bool)));
    connect(pingThread,SIGNAL(finished()),this,SLOT(deleteLater()));
    if(!pingThread->isRunning()){
        pingThread ->start();
    }

}


HttpClient *HttpClient::getobj(QString deviceType,QString deviceId){
    if (m_Instance == NULL)
    {
        qDebug() << "get Singleton instance success!";
        m_Instance = new HttpClient(deviceType,deviceId,NULL);
    }
    return m_Instance;
}
HttpClient *HttpClient::m_Instance = NULL;
HttpClient::GC HttpClient::gc;

/*HttpClient *HttpClient::mInstance = NULL;
HttpClient *HttpClient::getobj(QString deviceType,QString deviceId)
{
    if(mInstance == NULL)
        mInstance = new HttpClient(deviceType,deviceId,NULL);
    return mInstance;
}*/

HttpClient::~HttpClient()
{
    if(m_Instance)
    {
        delete m_Instance;
    }
    if(network_manager)
    {
        delete network_manager;
    }
}
void HttpClient::posNotGood(QString deviceType, QString deviceId, QString taskId, QString property, int iNotGood)
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("TaskId",taskId);
    obj.insert("Property",property);
    QJsonObject objTemp;
    objTemp.insert("NgProductCount", iNotGood);
    obj.insert("value", objTemp);

    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + DEVICE_TASK_INFO));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}
void HttpClient::posNotGood(QString deviceType, QString deviceId, QString taskId, QString property, QString strNotGood)
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("TaskId",taskId);
    obj.insert("Property",property);
    obj.insert("NgProductCount", strNotGood);

    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + DEVICE_TASK_INFO));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}


void HttpClient::posGongzhuang(QString deviceType, QString deviceId, QString taskId, QJsonObject tempObj)
{
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("TaskId",taskId);

    QNetworkRequest request;
    QJsonObject objGongZhuangData;
    objGongZhuangData.insert("ToolingCode", tempObj["ToolingCode"].toString());
    objGongZhuangData.insert("ToolingName", tempObj["ToolingName"].toString());
    obj.insert("ModuleId", objGongZhuangData);

    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;

    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    request.setUrl(QUrl(mServerSetting + GONGZHUANG));

    //设置url
    request.setUrl(QUrl(mServerSetting + POST_WARN_URL));

    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);

}

void HttpClient::postWarningInfo(QString deviceType, QString deviceId, QString taskId, QJsonObject tempObj)

{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("TaskId",taskId);

    QJsonObject objWarningData;
    objWarningData.insert("alarm", tempObj["alarm"].toString());
    objWarningData.insert("createTime", tempObj["createTime"].toString());
    obj.insert("AlarmData", objWarningData);

    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + POST_WARN_URL));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}

void HttpClient::posMaterial(QString deviceType, QString deviceId, QString taskId, QJsonObject tempObj)
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("TaskId",taskId);

    QJsonObject objMatarialData;
    objMatarialData.insert("count", tempObj["count"].toString());
    objMatarialData.insert("code", tempObj["mcode"].toString());
    objMatarialData.insert("mname", tempObj["mname"].toString());
    obj.insert("MaterialData", objMatarialData);

    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + Material));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}

void HttpClient::postWarningInfo(QString deviceType, QString deviceId, QString taskId, QJsonObject tempObj,
                                 bool b)
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    if(tempObj["AlarmType"].toString() == "Device" )
        obj.insert("TaskId", "");
    else
        obj.insert("TaskId",taskId);
    obj.insert("AlarmContent", tempObj["AlarmContent"].toString());
    obj.insert("UpdateTime",tempObj["UpdateTime"].toString());
    obj.insert("AlarmType",tempObj["AlarmType"].toString());


    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + POST_WARN_URL));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}






void HttpClient::posOperator(QString deviceType, QString deviceId, QString taskId, QJsonObject tempObj, DeviceState::DeviceStion dd)
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("TaskId",taskId);
    obj.insert("OperatorId", tempObj["OperatorId"].toString());
    obj.insert("Operator", tempObj["Operator"].toString());
    //obj.insert("createtime", tempObj["createtime"].toString());
    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    if( dd == DeviceState::OPERATOR_WORK_STATION )
    {
          request.setUrl(QUrl(mServerSetting + OPERATOR));
    }
    else if( dd  == DeviceState::FIRST_CHECK_STATION )
    {
          request.setUrl(QUrl(mServerSetting + FIRST_CHECK));
    }
    else if( dd  == DeviceState::QC_CHECK_STATION )
    {
          request.setUrl(QUrl(mServerSetting + QC));
    }
    else
    {
          request.setUrl(QUrl(mServerSetting + DIANJIAN));
    }

    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}

void HttpClient::registerDeviceInfo(QString deviceType, QString deviceId, QString property, QString value)
{
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString pro_test = utf8->toUnicode(property.toUtf8()).toUtf8();

    QString m_deviceType = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString m_deviceId = utf8->toUnicode(deviceId.toUtf8()).toUtf8();

    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("DeviceType",m_deviceType);
    json.insert("DeviceId",m_deviceId);
    json.insert("Property",pro_test);
    json.insert("Value",value);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(mServerSetting + REGISTER_DEVICE_INFO_URL));
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    DDDValue(dataArray);
    network_manager->post(network_request,dataArray);
}




void HttpClient::pos7Datas(QString deviceType, QString deviceId, QString taskId, QJsonArray arr )
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("TaskId",taskId);
    obj.insert("value", arr);

    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + NEW_PRODUCT_INFO));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}

//6 设备关机
void HttpClient::posShutDown(QString deviceType, QString deviceId, QString property, QString value)
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("Property",property);
    obj.insert("Value", value);
    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + REGISTER_DEVICE_INFO_URL));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}



//5 更新当日任务
void  HttpClient::posTodayTask(QString deviceType, QString deviceId, QString taskId, QString property, QJsonObject tempValueObj, int iType )
{
    //QJsonObject valueObj;
    //valueObj.insert("productname", tempValueObj["productname"].toString());
    //valueObj.insert("productcode", tempValueObj["productcode"].toString());
    //valueObj.insert("UpdateTime",  tempValueObj["UpdateTime"].toString());
    // if( tempValueObj["offtime"].toString().isEmpty() == false )
    //    valueObj.insert("offtime",  tempValueObj["offtime"].toString());
   // valueObj.insert("taskstatus", tempValueObj["taskstatus"].toString());

   /* if( iType == 0)
    {
        valueObj.insert("FinishedProduct", tempValueObj["FinishedProduct"].toString());
        valueObj.insert("TotalProductCount", tempValueObj["TotalProductCount"].toInt());
    }
    */
//    if( iType == 1 )
//        valueObj.insert("FinishedProduct", tempValueObj["FinishedProduct"].toString());
//        valueObj.insert("Weight", tempValueObj["Weight"].toString());
  /*
    if( iType == 2)
        valueObj.insert("TotalProductCount", tempValueObj["TotalProductCount"].toInt()); //压塑键TotalProductCount
 */

    //valueObj.insert("Energy", tempValueObj["Energy"].toString());
   // valueObj.insert("productcount", tempValueObj["productcount"].toString());
   // valueObj.insert( "taskyield", tempValueObj["taskyield"].toString());

    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("Energy",tempValueObj["Energy"].toString());
    obj.insert("Weight",tempValueObj["Weight"].toString());
    obj.insert("FinishedProduct",tempValueObj["FinishedProduct"].toString());
    obj.insert("UpdateTime",tempValueObj["UpdateTime"].toString());
  //obj.insert("TaskId",taskId);
  //obj.insert("Property",property);
  //obj.insert("value", valueObj);


    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    //request.setUrl(QUrl(mServerSetting + DEVICE_TASK_INFO));
     request.setUrl(QUrl(mServerSetting + HJWELDER_ENERGY_PROPERTY));//20181220 ChenJiangang add info for Haojing Welder Engrgy

    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
    dataArray.clear();
}

//4 更新设备状态
void HttpClient::posOrderInfo( QString deviceType,QString deviceId, QString property/*task*/, QString value)
{
    QNetworkRequest request;
    QJsonObject obj;
    obj.insert("DeviceType",deviceType);
    obj.insert("DeviceId",deviceId);
    obj.insert("Property",property);
    obj.insert("Value", value);
    QJsonDocument document;
    document.setObject(obj);
    QByteArray dataArray = document.toJson( QJsonDocument::Compact);
    QString concatenated = "admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    request.setUrl(QUrl(mServerSetting + REGISTER_DEVICE_INFO_URL));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(request,dataArray);
}


void HttpClient::posDeviceInfo(QString deviceType,QString deviceId,QString property,QString value)
{   
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString m_property = utf8->toUnicode(property.toUtf8()).toUtf8();
    QString m_deviceType = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString m_deviceId = utf8->toUnicode(deviceId.toUtf8()).toUtf8();
    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("DeviceType",m_deviceType);
    json.insert("DeviceId",m_deviceId);
    json.insert("Property",m_property);
    json.insert("Value",value);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(mServerSetting + REGISTER_DEVICE_INFO_URL));
    //设置认证
    //qDebug() << Q_FUNC_INFO << dataArray;
    //qDebug() << mServerSetting + REGISTER_DEVICE_INFO_URL;
    //    DDDValue(dataArray);
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(network_request,dataArray);
}

void HttpClient::posDeviceDetail(QString deviceType, QString deviceId, QString property, QString value)
{
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString pro_test = utf8->toUnicode(property.toUtf8()).toUtf8();
    QString m_deviceType = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString m_deviceId = utf8->toUnicode(deviceId.toUtf8()).toUtf8();
    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("DeviceType",m_deviceType);
    json.insert("DeviceId",m_deviceId);
    json.insert("Property",pro_test);
    json.insert("Value",value);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(mServerSetting + DEVICE_DETAIL_URL));
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(network_request,dataArray);
}

void HttpClient::putDeviceDetail(QString deviceType, QString deviceId, QString property, QString value)
{
    QString update_device =  /*HOST_IP*/ mServerSetting + "api/device_detail/";
    QString sep = "/";
    update_device.append(deviceType).append(deviceId).append(property).append(sep);

    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString pro_test = utf8->toUnicode(property.toUtf8()).toUtf8();
    QString m_deviceType = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString m_deviceId = utf8->toUnicode(deviceId.toUtf8()).toUtf8();
    QString m_update_device_url = utf8->toUnicode(update_device.toUtf8()).toUtf8();

    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("DeviceType",m_deviceType);
    json.insert("DeviceId",m_deviceId);
    json.insert("Property",pro_test);
    json.insert("Value",value);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(m_update_device_url));

    //DDDValue(m_update_device_url);
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->put(network_request,dataArray);
    update_device.clear();
}

void HttpClient::putUpdateDevice(QString deviceType, QString deviceId, QString property, QString value)
{
    QString update_device =  /*HOST_IP*/ mServerSetting + "api/device_info/";
    QString sep = "/";
    update_device.append(deviceType).append(deviceId).append(property).append(sep);
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString pro_test = utf8->toUnicode(property.toUtf8()).toUtf8();
    QString m_deviceType = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString m_deviceId = utf8->toUnicode(deviceId.toUtf8()).toUtf8();
    QString m_update_device_url = utf8->toUnicode(update_device.toUtf8()).toUtf8();
    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("DeviceType",m_deviceType);
    json.insert("DeviceId",m_deviceId);
    json.insert("Property",pro_test);
    json.insert("Value",value);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(m_update_device_url));
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->put(network_request,dataArray);
    dataArray.clear();
    update_device.clear();
}

void HttpClient::getUserInfo( QString userId)
{
    QString sep = "/";
    QString userUrl = QString(mServerSetting + USER_URL).append(userId).append(sep);
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString user_url = utf8->toUnicode(userUrl.toUtf8()).toUtf8();
    QNetworkRequest network_request;

    QString concatenated ="admin:admin123";
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    //    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(user_url));
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->get(network_request);
}

void HttpClient::postGetUserInfo(QString userId, QString station, QString deviceType, QString deviceId, QString taskId)
{
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString user_id = utf8->toUnicode(userId.toUtf8()).toUtf8();
    QString _station = utf8->toUnicode(station.toUtf8()).toUtf8();
    QString device_type = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString device_id = utf8->toUnicode(deviceId.toUtf8()).toUtf8();
    QString task_id = utf8->toUnicode(taskId.toUtf8()).toUtf8();
    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("UserId",user_id);
    json.insert("Station",_station);
    json.insert("DeviceType",device_type);
    json.insert("DeviceId",device_id);
    if(!taskId.isEmpty())
    {
        json.insert("TaskId",task_id);
    }
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(mServerSetting + USER_PERMISSION_URL));
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(network_request,dataArray);
}

void HttpClient::postOrderState(QString orderState, QString deviceType, QString deviceId, QString taskId)
{
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString order_state = utf8->toUnicode(orderState.toUtf8()).toUtf8();
    QString device_type = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString device_id = utf8->toUnicode(deviceId.toUtf8()).toUtf8();
    QString task_id = utf8->toUnicode(taskId.toUtf8()).toUtf8();
    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("State",order_state);
    json.insert("DeviceType",device_type);
    json.insert("DeviceId",device_id);
    if(!taskId.isEmpty())
    {
        json.insert("TaskId",task_id);
    }
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(mServerSetting + POST_ORDER_URL));
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->post(network_request,dataArray);
}

void HttpClient::putOrderState(QString orderState, QString deviceType, QString deviceId, QString taskId)
{
    QString update_device =  /*HOST_IP*/ mServerSetting + "production_order/api/production_order_state/";
    QString sep = "/";
    update_device.append(orderState).append(deviceType).append(deviceId).append(taskId).append(sep);
    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //汉字转UTF-8
    QString order_state = utf8->toUnicode(orderState.toUtf8()).toUtf8();
    QString device_type = utf8->toUnicode(deviceType.toUtf8()).toUtf8();
    QString device_id = utf8->toUnicode(deviceId.toUtf8()).toUtf8();
    QString task_id = utf8->toUnicode(taskId.toUtf8()).toUtf8();
    QString m_update_device_url = utf8->toUnicode(update_device.toUtf8()).toUtf8();
    QNetworkRequest network_request;
    QJsonObject json;
    json.insert("State",order_state);
    json.insert("DeviceType",device_type);
    json.insert("DeviceId",device_id);
    if(!taskId.isEmpty())
    {
        json.insert("TaskId",task_id);
    }
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    QString concatenated ="admin:admin123";/*"QT:Qt123456";*/
    QByteArray data = concatenated.toLocal8Bit().toBase64();
    QString headerData = "Basic " + data;
    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader,dataArray.length());
    //设置url
    network_request.setUrl(QUrl(m_update_device_url));
    //设置认证
    network_request.setRawHeader("Authorization",headerData.toLocal8Bit());
    network_manager->put(network_request,dataArray);
    update_device.clear();
}

/*
 * post 回应码 Created 201
 * put  回应码 OK 200
 */
void HttpClient::replyFinish(QNetworkReply *reply)
{
    if(reply&&reply->error()== QNetworkReply::NoError)
    {
        QByteArray replyData = reply->readAll();
        /*QTextCodec *codec = QTextCodec::codecForName("UTF-8");//Last is GBK 20180428
        QString s;
        s = codec->toUnicode(replyData);
        qDebug() << Q_FUNC_INFO <<s;*/
        QJsonParseError jsonErr;
        QJsonDocument myjsonDoc1 = QJsonDocument::fromJson(replyData,&jsonErr);
        if(jsonErr.error == QJsonParseError::NoError)
        {
            if(!myjsonDoc1.isEmpty())
            {
                if(myjsonDoc1.isObject())
                {
                    QJsonObject jobj = myjsonDoc1.object();
                    if(jobj.contains("Station"))
                    {
                        QString station = jobj.value("Station").toString();
                        emit sendStation_OfHttp(station);
                    }
                    if(jobj.contains("Permission"))
                    {
                        QString permission = jobj.value("Permission").toString();
                        //qDebug() << "=====PERMISSION : "  << permission;
                        getUserPermission(permission);
                        emit sendUserPerssion(permission);
                    }
                    if(jobj.contains("Property"))
                    {
                        QString Property = jobj.value("Property").toString();
                        if(Property.compare("TaskId") == 0)
                        {
                            // emit postSerialNum_Signals(); //TODO 20180718 remove for test
                        }
                        else if(Property.compare("ProductName") == 0)
                        {
                            emit updateDeviceState_Signals();
                        }
                    }

                    if(jobj.contains("Value"))
                    {
                        QString state = jobj.value("Value").toString();
                        if(state.compare("processing") == 0)
                        {
                            emit orderConfirmOK();
                        }
                    }
                    if(jobj.contains("User"))
                    {
                        QString user = jobj.value("User").toString();
                        //qDebug() << user;
                        emit getUserStrirng(user);
                    }
                    QJsonObject::iterator it = jobj.begin();
                    while (it != jobj.end())
                    {
                        switch (it.value().type()) {
                        case QJsonValue::String:
                        {
                            QString property = it.value().toString();
                            if(property.compare("register",Qt::CaseInsensitive)==0/*jobj.value("Property").toString().compare("register")==0*/ && reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().compare("Created",Qt::CaseInsensitive)==0)
                            {
                                posDeviceInfo(m_deviceType,m_deviceId,"heartbeat","on-line");
                                posDeviceInfo(m_deviceType,m_deviceId,"IP",getLocalHostIP());
                                posDeviceInfo(m_deviceType,m_deviceId,"MAC",macAddress());
                                posDeviceInfo(m_deviceType,m_deviceId,"VideoIP",VideoIp::getVideoIp());
                                posDeviceInfo(m_deviceType,m_deviceId,"Port","4000");
                                posDeviceInfo(m_deviceType,m_deviceId,"State","idle");
                                emit registerOK(true);
                            }
                            if(property.compare("heartbeat",Qt::CaseInsensitive)==0/*jobj.value("Property").toString().compare("heartbeat")==0*/ && reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().compare("Created",Qt::CaseInsensitive)==0)
                            {
                                //                                posDeviceInfo(m_deviceType,m_deviceId,"IP",getLocalHostIP());
                            }
                            if(property.compare("IP",Qt::CaseInsensitive)==0/*jobj.value("Property").toString().compare("IP")==0*/ && reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().compare("Created",Qt::CaseInsensitive)==0)
                            {
                                //                                posDeviceInfo(m_deviceType,m_deviceId,"MAC",macAddress());
                                //                                posDeviceInfo(m_deviceType,m_deviceId,"Port","4000");
                                //                                posDeviceInfo(m_deviceType,m_deviceId,"state","idle");
                            }
                            if(property.compare("MAC",Qt::CaseInsensitive)==0 && reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString().compare("Created",Qt::CaseInsensitive)==0)
                            {

                                //qDebug() << "\n\n\n\n\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~START WORK";
                                emit startHttpWork();
                            }
                        }
                            break;
                        default:
                            break;
                        }
                        it++;
                    }
                }
            }
        }
    }
    else
    {
        DDDValue(reply->error());
        //        DDDValue(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
    }
    reply->abort();
    reply->close();
    reply->deleteLater();
}

void HttpClient::receiIpStatus(bool status)
{    emit ipStatusSignals(status);
}

QString HttpClient::getLocalHostIP()
{
    QList<QHostAddress> AddressList = QNetworkInterface::allAddresses();
    QHostAddress result;
    foreach(QHostAddress address, AddressList){
        if(address.protocol() == QAbstractSocket::IPv4Protocol &&
                address != QHostAddress::Null &&
                address != QHostAddress::LocalHost){
            if (address.toString().contains("127.0.")){
                continue;
            }
            result = address;
            break;
        }
    }
    return result.toString();
}

QString HttpClient::macAddress()
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    return strMacAddr;
}

bool HttpClient::ping(QString ip)
{
    int exitCode;
    QString strArg = "ping -s 1 -c 1 " + ip; //linux platform
    exitCode = QProcess::execute(strArg);
    if(0 == exitCode)
    {
        //it's alive
        //        qDebug() << "shell ping " + ip + "sucessed";
        return true;
    }
    else
    {
        //        qDebug() << "shell ping " + ip + "failed";
        return false;
    }
}

int HttpClient::getUserPermission(QString permissionString)
{
    if (permissionString.compare("yes",Qt::CaseInsensitive) == 0) {
        m_permission = 1;
        GlobalVar::getobj()->setUserPermission(m_permission);
        return m_permission;
    }
    else if (permissionString.compare("no",Qt::CaseInsensitive) == 0) {
        m_permission = 0;
        GlobalVar::getobj()->setUserPermission(m_permission);
        return m_permission;
    }
    else {
        m_permission = -1;
        GlobalVar::getobj()->setUserPermission(m_permission);
        return m_permission;
    }
}

int HttpClient::getUserPermission()
{
    return m_permission;
}
